import { type Ref, onBeforeUnmount, onMounted } from 'vue'
import { useStatementStore } from '@/store'

export default function useArrowKey(
  inputIndex: Ref<number>,
  lengthPerRow?: number,
) {
  const { statementFlattenColumns } = useStatementStore()
  function eventHandler(e: KeyboardEvent): boolean | void {
    const { key, keyCode } = e
    if (keyCode < 37 || keyCode > 40 || !key.includes('Arrow')) {
      return false
    }
    const inputs = document.querySelectorAll('.input-cell input')
    let _inputIndex = toValue(inputIndex)
    // TODO
    const length = lengthPerRow ?? statementFlattenColumns.length
    // ArrowUp
    if (key === 'ArrowUp' || keyCode === 38) {
      _inputIndex -= length
    }
    // ArrowDown
    if (key === 'ArrowDown' || keyCode === 40) {
      _inputIndex += length
    }
    // ArrowLeft
    if (key === 'ArrowLeft' || keyCode === 37) {
      _inputIndex--
    }
    // ArrowRight
    if (key === 'ArrowRight' || keyCode === 39) {
      _inputIndex++
    }

    _inputIndex = Math.max(0, _inputIndex)
    _inputIndex = Math.min(inputs.length - 1, _inputIndex)

    inputIndex.value = _inputIndex

    const input = inputs[_inputIndex] as HTMLInputElement
    if (input) {
      input.click()
      input.scrollIntoView(false)
    }
  }

  // 绑定方向快捷键事件
  function bindArrowKeyEvent() {
    document.addEventListener('keyup', eventHandler, false)
  }

  // 解除绑定方向快捷键事件
  function unbindArrowKeyEvent() {
    document.removeEventListener('keyup', eventHandler, false)
  }

  onBeforeUnmount(() => {
    unbindArrowKeyEvent()
  })

  onMounted(() => {
    bindArrowKeyEvent()
  })
}
